import os
import time
import re,json
import serverFiles

def find_chinese_strings_in_vue_files(directory):
    chinese_strings = []

    # 遍历指定目录下的所有 .vue 文件
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.vue'):
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()

                     # 使用正则表达式匹配 $t(...) 中的中文字符串，支持单引号和双引号
                    matches = re.findall(r'\$t\([\'"]([\u4e00-\u9fa5]+(?:[^\'"]*[\u4e00-\u9fa5]+)*)[\'"]\)', content)
                   
                    chinese_strings.extend(matches)

    # 去除重复的中文字符串
    unique_chinese_strings = list(set(chinese_strings))

    return unique_chinese_strings



def find_chinese_desc(json_object, key='Desc'):
    found_values = []

    if isinstance(json_object, dict):
        for k, v in json_object.items():
            if k == key and is_chinese_or_mixed_string(v):
                found_values.append(v)
            elif isinstance(v, (dict, list)):
                found_values.extend(find_chinese_desc(v, key))

    elif isinstance(json_object, list):
        for item in json_object:
            found_values.extend(find_chinese_desc(item, key))

    return found_values

def is_chinese_or_mixed_string(string):
    has_chinese = re.search(r'[\u4e00-\u9fa5]', string)
    is_not_empty = len(string) > 0
    return all([has_chinese, is_not_empty])

# 指定要遍历的目录
directory = '../page'

# 获取并打印所有需要翻译的中文字符串（去除重复）
unique_chinese_strings = find_chinese_strings_in_vue_files(directory)
strings = find_chinese_desc(serverFiles.dataSource)
strings_to_add = list(set(unique_chinese_strings + strings))
# print(unique_chinese_strings)



def add_strings_to_file(strings, file_path):
    base_timestamp = int(time.time() * 1000)

    with open(file_path, "r", encoding="utf-8") as file:
        content = json.load(file)

    # 向 BasicDict 添加字符串
    for string in strings:
        if string not in content["BasicDict"]:
            content["BasicDict"][string] = base_timestamp
            base_timestamp += 1

    # 向 Dicts 的特定元素添加字符串
    indices_to_update = [4, 19, 20]
    for index in indices_to_update:
        for string in strings:
            if string not in content["Dicts"][index]:
                content["Dicts"][index][string] = string

    # print(content)
    # 将更改后的内容写回文件
    with open(file_path, "w", encoding="utf-8") as file:
        json.dump(content, file, ensure_ascii=False, indent=4)

# 示例用法
# strings_to_add = ['新字符串1', '新字符串2', '新字符串3']
file_path = r"C:\Users\jan\Documents\Project\CproScada\server\dict\project.dict"
print(strings_to_add)

# add_strings_to_file(strings_to_add, file_path)
#此函数接受一个字符串数组和一个文件路径作为参数。它首先从给定的文件路径读取 JSON 内容。然后，将字符串添加到 "BasicDict"（值为时间戳）、"Dicts" 第四列（索引为3）、第19列（索引为18）和第20列（索引为19）。最后，将更改后的内容写回文件。
# print(serverFiles.prj_dict['Dicts'][4])


